package com.richard.base.net.interceptors;


import android.text.TextUtils;


import com.richard.base.net.utils.DiffTimeUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ll
 * on 2018/8/21
 */
public class BasicParamsInterceptor implements Interceptor {
    private int serverTimeCount;

    public BasicParamsInterceptor() {

    }
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        checkServerDateTime(response.header("Date"));
        return response;
    }

    private void checkServerDateTime(String date) {
        if (TextUtils.isEmpty(date)) {
            return;
        }
        serverTimeCount++;
        if (serverTimeCount % 8 == 0) {

            String serverTime = date;
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date serverDateGMT = null;
            try {
                serverDateGMT = sdf.parse(serverTime);
                long diff = serverDateGMT.getTime() - System.currentTimeMillis();

                if (Math.abs(diff) > DiffTimeUtils.DIFFHOURADJUST) {
                    DiffTimeUtils.setDiffMs(diff);
                } else {
                    DiffTimeUtils.setDiffMs(0L);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
